import {Component, ElementRef, NgZone, OnDestroy, OnInit} from '@angular/core';
import {BaseTabPage} from '../../common/baseTabPage';
import {Events, NavController, ToastController} from '@ionic/angular';
import {HttpService} from '../../services/http.service';
import * as authReducer from '../../reducers/auth.reducer';
import {select, Store} from '@ngrx/store';
import {Storage} from '@ionic/storage';
import {AppConfig} from '../../common/app-config.enum';
import {UrlAndOPT} from '../../common/url-and-opt.enum';
import {ActivatedRoute} from '@angular/router';

@Component({
  selector: 'app-loan',
  templateUrl: './loan.page.html',
  styleUrls: ['./loan.page.scss'],
})
export class LoanPage extends BaseTabPage implements OnInit, OnDestroy {

  public userInfo: authReducer.UserModel;
  isLogin = false; // 是否登录
  flowchart: { [key: number]: any } = { // 流程图
    2: {
      isDone: false,
      excuteDate: null,
      status: 0,
      comment: '会员信息'
    },
    3: {
      isDone: false,
      excuteDate: null,
      status: 0,
      comment: '提交初审'
    },
  };

  type: any; // 借款类型

  constructor(public zone: NgZone,
              public elRef: ElementRef,
              private navCtrl: NavController,
              public toastCtrl: ToastController,
              private events: Events,
              private store: Store<authReducer.AuthState>,
              private storage: Storage,
              private routeInfo: ActivatedRoute,
              private service$: HttpService
  ) {
    super(zone, elRef);
    // 侦听登录状态变化
    this.store.pipe(select(authReducer.getAuth))
      .subscribe(authState => {
        this.userInfo = {...authState.userInfo};
        this.isLogin = !!this.userInfo && !!this.userInfo[AppConfig.USER_INFO_KEY];
      });
    // 订阅流程数据变化通知
    this.events.subscribe(AppConfig.TOPIC_UNDO_LIST, () => {
      this.getData();
    });
  }

  async ngOnInit() {
    this.userInfo = await this.storage.get(AppConfig.USER_INFO);
    if (this.userInfo && this.userInfo[AppConfig.USER_INFO_KEY]) {
      this.isLogin = true;
      this.getData();
    }
    // 获取header中的元素
    this.getTopElement();
  }

  ngOnDestroy() {
    // 取消订阅
    this.events.unsubscribe(AppConfig.TOPIC_UNDO_LIST);
  }

  private getData(event?) {
    this.type = this.routeInfo.snapshot.params; // 获取借款类型(其中包含userRole和from参数)
    const params = this.type['id'] ? {productId: this.type['id']} : {}; // 判断类型是否存在
    this.service$.doRequest(UrlAndOPT.loan_process, params)
      .subscribe(obj => {
        if (obj) {
          this.flowchart = obj['obj'];
        }
        if (event) {  // 如果为下拉刷新，关闭下拉组件
          event.target.complete();
        }
      }, () => {
        if (event) {
          event.target.complete();
        }
      });
  }

  // 下拉刷新标的信息
  doRefresh(event) {
    this.getData(event);
  }

  doUndo(value: boolean, key: number) {
    if (value['canUse']) {
      this.service$.doUndo(2, this.service$.undoList_loan[key], this.userInfo[AppConfig.USER_TYPE_KEY], this.type);
    } else {
      let msg = '不可操作';
      if (value['isDone']) {
        msg = '此步骤已完成';
      } else {
        msg = '尚不能进行此操作，请先完成前置步骤';
      }
      this.showToast(msg);
    }
  }

  goBack() {
    const from = this.type['from'] || '/tabs/home';
    this.navCtrl.navigateBack([from]);
  }

  async showToast(txt: string) {
    const toast = await this.toastCtrl.create({
      message: txt,
      position: AppConfig.TOAST_POSITION,
      duration: AppConfig.TOAST_DURATION * 1
    });
    return toast.present();
  }

}
